//
//  GoodsDetailViewController.m
//  JiuJiuShangCheng
//
//  Created by jiujiukeji on 2018/7/11.
//  Copyright © 2018年 jiujiukeji. All rights reserved.
//

#import "SalesDetailViewController.h"
#import "SDCycleScrollView.h"
#import "JiFenDetailBottomV.h"
#import "GoodsDetailItemTableViewCell.h"
#import "CommentViewController.h"
#import "BuyViewController.h"
#import "GuiGeTopView.h"

@interface SalesDetailViewController ()<UITableViewDelegate,UITableViewDataSource,SDCycleScrollViewDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) SDCycleScrollView *cycleScrollView; // 轮播图
@property (nonatomic, strong) NSMutableArray *netImages; // 网络图片数组
@property (nonatomic, strong) NSDictionary *goodsDic;
@property (nonatomic, assign) CGSize sizeLen1;
@property (nonatomic, assign) CGSize sizeLen2;
@property (nonatomic, strong) JiFenDetailBottomV *goodsDetailBottomV;
@property (nonatomic, strong) UIButton *jiaBtn;
@property (nonatomic, strong) UIButton *jianBtn;
@property (nonatomic, assign) NSInteger num;
@property (nonatomic, strong) UILabel *numLB;

@end

@implementation SalesDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = UIColorWhite;
    
    [self setUpUI];
    [self getGoodsDetail];
    [self isCollect];
}
#pragma mark - 获取商品详情
- (void)getGoodsDetail
{
    if (self.contentId) {
        [MBProgressHUD showMessage:nil toView:self.view];
        [TFNetworking getWithURLString:[NSString stringWithFormat:@"%@/api/json/content/content.ashx?action=content&companyid=%@&id=%@",kServerURL,companyId,self.contentId] parameters:nil success:^(id responseObject) {
            [MBProgressHUD hideHUDForView:self.view];
            
            if ([responseObject[@"status"] intValue] == 1) {
                self.goodsDic = responseObject[@"content"][0];
                self.sizeLen1 = [self.goodsDic[@"title"] boundingRectWithSize:CGSizeMake (rateWidth(660), MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:15]} context:nil].size;
                self.sizeLen2 = [self.goodsDic[@"text1"] boundingRectWithSize:CGSizeMake (rateWidth(660), MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:14]} context:nil].size;
            }
            
            [self.tableView reloadData];
            
        } failure:^(NSError *error) {
            [TFHUD addRemindHUD:self.view message:@"网络不给力..."];
            
        }];
    }
}
#pragma mark - 判断收藏
- (void)isCollect
{
    if (self.contentId) {
        [MBProgressHUD showMessage:nil toView:self.view];
        [TFNetworking getWithURLString:[NSString stringWithFormat:@"%@/api/json/content/content.ashx?action=checkcollection&companyid=%@&id=%@",kServerURL,companyId,self.contentId] parameters:nil success:^(id responseObject) {
            [MBProgressHUD hideHUDForView:self.view];
            
            if ([responseObject[@"status"] intValue] == 0) {
                // 已收藏
                [self.goodsDetailBottomV.collectBtn setImage:UIImageNamed(@"detailshoucang1") forState:(UIControlStateNormal)];
            } else if ([responseObject[@"status"] intValue] == 2) {
                // 未收藏
                [self.goodsDetailBottomV.collectBtn setImage:UIImageNamed(@"detailshoucang") forState:(UIControlStateNormal)];
            }
            
            
        } failure:^(NSError *error) {
            [TFHUD addRemindHUD:self.view message:@"网络不给力..."];
            
        }];
    }
}
#pragma mark - 收藏/取消收藏
- (void)setCollect
{
    if (self.contentId) {
        [MBProgressHUD showMessage:nil toView:self.view];
        [TFNetworking getWithURLString:[NSString stringWithFormat:@"%@/api/json/content/content.ashx?action=collection&companyid=%@&id=%@",kServerURL,companyId,self.contentId] parameters:nil success:^(id responseObject) {
            [MBProgressHUD hideHUDForView:self.view];
            
            if ([responseObject[@"status"] intValue] == 1) {
                // 收藏成功
                [self.goodsDetailBottomV.collectBtn setImage:UIImageNamed(@"detailshoucang1") forState:(UIControlStateNormal)];
            } else if ([responseObject[@"status"] intValue] == 2) {
                // 取消收藏成功收藏
                [self.goodsDetailBottomV.collectBtn setImage:UIImageNamed(@"detailshoucang") forState:(UIControlStateNormal)];
            }
            
            
        } failure:^(NSError *error) {
            [TFHUD addRemindHUD:self.view message:@"网络不给力..."];
            
        }];
    }
}
#pragma mark - 立即购买
- (void)buyAction
{
    if (self.contentId) {

        [MBProgressHUD showMessage:nil toView:self.view];
        [TFNetworking getWithURLString:[NSString stringWithFormat:@"%@/api/json/shop/shop.ashx?action=shoping&companyid=%@&id=%@&s=%@&r=%@&from=mobile",kServerURL,companyId,self.contentId,[NSString stringWithFormat:@"%ld",self.num],@"1"] parameters:nil success:^(id responseObject) {
            [MBProgressHUD hideHUDForView:self.view];
            if ([responseObject[@"status"] intValue] == 10) {
                BuyViewController *buyVC = [[BuyViewController alloc] init];
                buyVC.selectIdArray = @[responseObject[@"CartId"]];
                [self.navigationController pushViewController:buyVC animated:YES];
            } else {
                [MBProgressHUD showError:responseObject[@"errMsg"]];
            }
            
        } failure:^(NSError *error) {
            [TFHUD addRemindHUD:self.view message:@"网络不给力..."];
            
        }];
    }
    
}
- (void)setUpUI
{
    self.num = 1;
    [self.view addSubview:self.tableView];
    JiFenDetailBottomV *bottomV = [[JiFenDetailBottomV alloc] initWithFrame:CGRectMake(0, kScreenHeight-rateHeight(100), kScreenWidth, rateHeight(100))];
    [bottomV.buyBtn setTitle:@"立即抢购" forState:(UIControlStateNormal)];
    [bottomV.buyBtn addTarget:self action:@selector(buyAction) forControlEvents:(UIControlEventTouchUpInside)];
    self.goodsDetailBottomV = bottomV;
    [self.view addSubview:bottomV];
    [bottomV.collectBtn addTarget:self action:@selector(setCollect) forControlEvents:(UIControlEventTouchUpInside)];
}
#pragma mark - tableView delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 4;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    } else if (section == 1) {
        return 1;
    } else if (section == 2) {
        return 2;
    } else {
        return 1;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 2 || indexPath.section == 3) {
        GoodsDetailItemTableViewCell *cell = [[GoodsDetailItemTableViewCell alloc] init];
        if (indexPath.section == 2) {
            NSArray *array = @[@"选择数量",@"商品评价"];
            cell.leftLB.text = array[indexPath.row];
            if (indexPath.row == 0) {
                cell.arrow.hidden = YES;
                // 数量编辑
                UIImageView *editImg = [[UIImageView alloc] init];
                editImg.image = UIImageNamed(@"numEditImg");
                [editImg sizeToFit];
                [cell.contentView addSubview:editImg];
                [editImg mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.right.equalTo(cell.contentView).offset(-rateWidth(40));
                    make.centerY.equalTo(cell.contentView);
                }];
                editImg.userInteractionEnabled = YES;
                
                UILabel *numLB = [UILabel labelWithText:[NSString stringWithFormat:@"%ld",self.num] textColor:UIColorFromRGB(0x666666) fontSize:13];
                [numLB sizeToFit];
                [editImg addSubview:numLB];
                [numLB mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.center.equalTo(editImg);
                }];
                self.numLB = numLB;
                
                self.jiaBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
                [cell.contentView addSubview:_jiaBtn];
                [_jiaBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.size.mas_offset(CGSizeMake(30, 50));
                    make.centerX.equalTo(editImg.mas_right);
                    make.centerY.equalTo(editImg);
                }];
                self.jianBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
                [cell.contentView addSubview:_jianBtn];
                [_jianBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.size.mas_offset(CGSizeMake(30, 50));
                    make.centerX.equalTo(editImg.mas_left);
                    make.centerY.equalTo(editImg);
                }];
                [_jiaBtn addTarget:self action:@selector(jiaAction) forControlEvents:(UIControlEventTouchUpInside)];
                [_jianBtn addTarget:self action:@selector(jianAction) forControlEvents:(UIControlEventTouchUpInside)];
                
            }
        } else {
            cell.leftLB.text = @"图文详情";
        }
        cell.selectionStyle = NO;
        return cell;
    } else {
        UITableViewCell *cell = [[UITableViewCell alloc] init];
        if (indexPath.section == 0) {
            // 轮播图
            if (self.goodsDic[@"imagesAll"]) {
                self.netImages = [NSMutableArray array];
                NSArray *array = [self.goodsDic[@"imagesAll"] componentsSeparatedByString:@","];
                for (NSString *str in array) {
                    [self.netImages addObject:[NSString stringWithFormat:@"http:%@",str]];
                }
                [cell.contentView addSubview:self.cycleScrollView];
                UIButton *btn1 = [UIButton buttonWithType:(UIButtonTypeCustom)];
                [btn1 setImage:UIImageNamed(@"detailfanhui") forState:(UIControlStateNormal)];
                [btn1 sizeToFit];
                [cell.contentView addSubview:btn1];
                [btn1 mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.left.equalTo(cell.contentView).offset(rateWidth(25));
                    make.top.equalTo(cell.contentView).offset(rateHeight(75));
                }];
                [btn1 addTarget:self action:@selector(back) forControlEvents:(UIControlEventTouchUpInside)];
                
                UIButton *btn2 = [UIButton buttonWithType:(UIButtonTypeCustom)];
                [btn2 setImage:UIImageNamed(@"detailfenxaing") forState:(UIControlStateNormal)];
                [btn2 sizeToFit];
                [cell.contentView addSubview:btn2];
                [btn2 mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.right.equalTo(cell.contentView).offset(-rateWidth(25));
                    make.top.equalTo(cell.contentView).offset(rateHeight(75));
                }];
            }
        } else if (indexPath.section == 1) {
            UILabel *label1 = [UILabel labelWithText:self.goodsDic[@"title"] textColor:UIColorFromRGB(0x323232) fontSize:15];
            [label1 sizeToFit];
            label1.numberOfLines = 0;
            [cell.contentView addSubview:label1];
            [label1 mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(cell.contentView).offset(rateWidth(30));
                make.top.equalTo(cell.contentView).offset(rateWidth(30));
                make.width.mas_lessThanOrEqualTo(@(rateWidth(660)));
                //                    make.height.mas_lessThanOrEqualTo(@(rateHeight(80)));
            }];
            UILabel *label11 = [UILabel labelWithText:self.goodsDic[@"text1"] textColor:UIColorFromRGB(0x666666) fontSize:14];
            [label11 sizeToFit];
            label11.numberOfLines = 0;
            [cell.contentView addSubview:label11];
            [label11 mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(cell.contentView).offset(rateWidth(30));
                make.top.equalTo(label1.mas_bottom).offset(rateWidth(20));
                make.width.mas_lessThanOrEqualTo(@(rateWidth(660)));
                //                    make.height.mas_lessThanOrEqualTo(@(rateHeight(70)));
            }];
            UILabel *label2 = [UILabel labelWithText:[NSString stringWithFormat:@"￥%.2f",[self.goodsDic[@"price"] floatValue]] textColor:UIColorFromRGB(0xf55555) fontSize:18];
            [label2 sizeToFit];
            [cell.contentView addSubview:label2];
            [label2 mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(label1);
                make.top.equalTo(label11.mas_bottom).offset(rateWidth(20));
            }];
            
            if (self.goodsDic[@"title"]) {
                NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:self.goodsDic[@"title"]];
                [str addAttribute:NSForegroundColorAttributeName value:UIColorFromRGB(0xf55555) range:NSMakeRange(0,6)];
                label1.attributedText = str;
            }
            
        }
        
        cell.selectionStyle = NO;
        return cell;
    }
    
}
- (void)jiaAction
{
    self.num++;
    self.numLB.text = [NSString stringWithFormat:@"%ld",self.num];
}
- (void)jianAction
{
    if (self.num>1) {
        self.num--;
        self.numLB.text = [NSString stringWithFormat:@"%ld",self.num];
    }
}
- (void)back
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return kScreenWidth;
    } else if (indexPath.section == 1) {
        return rateWidth(140)+_sizeLen1.height+_sizeLen2.height;
    } else {
        return rateWidth(90);
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.01;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section == 1 || section == 2) {
        return rateWidth(10);
    } else {
        return 0.01;
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 2 && indexPath.row == 1) {
        // 评论
        CommentViewController *commentVC = [[CommentViewController alloc] init];
        [self.navigationController pushViewController:commentVC animated:YES];
    }
}
#pragma mark - 轮播图
- (SDCycleScrollView *)cycleScrollView
{
    if (!_cycleScrollView) {
        // 轮播图
        _cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenWidth) delegate:self placeholderImage:[UIImage imageNamed:@"placeholder"]];
        _cycleScrollView.delegate = self;
        _cycleScrollView.showPageControl = YES;
        //        _cycleScrollView.pageDotColor = UIColorWithRGB(128, 130, 132);
        //        _cycleScrollView.currentPageDotColor = UIColorWithRGB(173, 36, 36);
        
        _cycleScrollView.pageDotImage = UIImageNamed(@"segmentGray");
        _cycleScrollView.pageControlDotSize = CGSizeMake(rateWidth(15), rateWidth(15));
        _cycleScrollView.currentPageDotImage = UIImageNamed(@"segmentRed");
        
        // 模拟延迟加载
        __weak typeof(self) weakSelf = self;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            weakSelf.cycleScrollView.imageURLStringsGroup = weakSelf.netImages;
        });
        // 清除缓存
        [self.cycleScrollView clearCache];
    }
    return _cycleScrollView;
}
#pragma mark - 轮播图点击
#pragma mark - SDCycleScrollViewDelegate
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index
{
    NSLog(@"---点击了第%ld张图片", index);
    
}
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, -TopHeight, kScreenWidth, kScreenHeight+TopHeight-rateHeight(100)) style:(UITableViewStyleGrouped)];
        _tableView.backgroundColor = tableViewBgColor;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = NO;
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
    }
    return _tableView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
